//接口https://naodongapi.zongheng.com/planet/ranks?pageNum=1&pageSize=10&isFavorite=1&rankType=5
//isFavorite=1 默认都是1
//rankNo=202509 日期 默认是202509
//月票ranktype=5
//热销ranktype=3 periodtype=0 日榜 periodtype=2 月榜
//点击rankType=0
//推荐ranktype=7
//捧场ranktype=8
//完结ranktype=9
// const centBookNamePaiming = document.querySelectorAll('.cent-bookName--paiming')
const yuepiao = document.querySelector('.yuepiao')
const yuepiao1 = document.querySelector('.yuepiao1')
const yuepiao2 = document.querySelector('.yuepiao2')
const page = document.querySelector('.page')
const crown = document.querySelector('.crown')
const rankLeft = document.querySelectorAll('.rankLeft-list')
const section = document.querySelector('section')
const iptDate = document.querySelector('.ipt-date')
const qiehuan = document.querySelector('.qiehuan')
const day = document.querySelector('.day')
const month = document.querySelector('.month')
let updatetime = 0
let rankType = 5
let itemCount = 0
let pageSize = 10
let currentPage = 1
let isNewBook = 1

const formatTime = (timeString) => {
    if (!timeString) return '暂无更新';
    // 创建Date对象
    const date = new Date(timeString);
    // 检查日期是否有效
    if (isNaN(date.getTime()) || date.getTime() <= 0) return '暂无更新';
    
    // 格式化为 YYYY-MM-DD HH:mm:ss（不使用padStart）
    const year = date.getFullYear();
    const months = date.getMonth() + 1;
    const days = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    // 手动补零
    const formatNumber = (num) => {
        return num < 10 ? '0' + num : num;
    };
    
    return `${year}-${formatNumber(months)}-${formatNumber(days)} ${formatNumber(hours)}:${formatNumber(minutes)}:${formatNumber(seconds)}`;
}
const getData = (pageNum=1,pageSize=10,isFavorite=1,rankType=5,isNewBook=1,periodType)=>{
    currentPage = pageNum
    const params = {
        pageNum,
        pageSize,
        isFavorite,
        rankType,
        isNewBook
    }
    if (periodType !== undefined) {
        params.periodType = periodType
    }
    axios.get('https://naodongapi.zongheng.com/planet/ranks?',{
        params:params
    }).then(res=>{
        // console.log(1)
        console.log(res.data.result) 
        itemCount = parseInt(res.data.result.itemCount)
        // console.log(itemCount)
        
        page.innerHTML = ''
        res.data.result.items.forEach((item,index)=>{
            
            const itemIndex = (pageNum - 1) * pageSize + index + 1
            const formattedTime = formatTime(item.newestChapter.updateTime);
            page.innerHTML+=`
            <div class="book-item">
                <div class="item-left"  onclick="ju()">
                    <a>
                        <div class="label" >${itemIndex}</div>
                        <img src="${item.coverUrl}">
                    </a>
                </div>
                <div class="item-mid">
                    <div class="cent-bookName">
                        <a>
                            <div class="cent-bookName--name"  onclick="ju()">${item.bookName}</div>
                        </a>
                        <div class="cent-bookName--paiming">
                            <span class="yuepiao">月票:</span>
                            <span class="people">${item.rankTrend}</span>
                        </div>
                    </div>
                    <div class="authLabe">
                        <div class="author">
                            <a onclick="author_jump(${item.authorId})">${item.authorName}</a>
                        </div>
                        <div class="sp-split"></div>
                        <div class="labelList">${item.categoryPname}</div>
                        <div class="sp-dot"></div>
                        <div class="labelList">${item.categoryName}</div>
                        <div class="sp-split"></div>
                        <div class="islianzai">连载中</div>
                    </div>
                    <div class="cent-jianjie">${item.description}</div>
                    <div class="cent-bokB">
                        <div class="gengxin">
                            <a>最近更新：${item.newestChapter.title}</a>                                  
                        </div>
                        <div class="time" style="padding-left: 24px;">2025-09-06 06:16:00</div>
                    </div>
                </div>
                <div class="item-right">
                    <p class="read">立即阅读</p>
                    <p class="add">加入书架</p>
                </div>
            </div>

            `
            // console.log(item.newestChapter.chapterId)
        })
    // 更新分页组件
    renderPagination()

    }).catch(err=>{
        console.log(err)
    })
}
const hiddenyuepiao = ()=>{

        if(rankType==0||rankType==7||rankType==8||rankType==9){
            section.style.display = 'none'
            iptDate.style.display = 'none'
            qiehuan.style.display = 'none'
            document.querySelectorAll('.cent-bookName--paiming').forEach(el => {
                el.style.display = 'none'
            })

        }else if(rankType==5){
            section.style.display = 'flex'
            iptDate.style.display = 'flex'
            qiehuan.style.display = 'none'
            document.querySelectorAll('.cent-bookName--paiming').forEach(el => {
                el.style.display = 'block'
            })
            
        }else if(rankType==3){
            section.style.display = 'none'
            iptDate.style.display = 'none'
            qiehuan.style.display = 'block'
            document.querySelectorAll('.cent-bookName--paiming').forEach(el => {
                el.style.display = 'none'
            })

        }
    
}
yuepiao1.onclick = ()=>{
    yuepiao2.classList.remove('section-active')
    yuepiao1.classList.add('section-active')
    page.innerHTML =''
    getData()
}
yuepiao2.onclick = ()=>{
    yuepiao1.classList.remove('section-active')
    yuepiao2.classList.add('section-active')
    page.innerHTML =''
    isNewBook = 2
    getData(currentPage, pageSize, 1, rankType, isNewBook)
}

for(let i=0; i<rankLeft.length; i++){
    rankLeft[i].onclick = ()=>{
        // 移除所有元素的 isActive 类
        rankLeft.forEach(element => {
            element.classList.remove('isActive');
        });
        // 为当前点击的元素添加 isActive 类
        rankLeft[i].classList.add('isActive');
        // 获取 data-type 属性值
        rankType = rankLeft[i].getAttribute('data-type');
        console.log(rankType);
        // 清空页面内容
        page.innerHTML = '';
        // 调用 getData 函数，传入对应的 rankType
        getData(1, 10, 1, parseInt(rankType)); // 使用 parseInt 将字符串转换为数字

        hiddenyuepiao()
    }
}
day.onclick = ()=>{
    month.classList.remove('span_active')
    day.classList.add('span_active')
    page.innerHTML =''
    periodType = 0
    getData(1,10,1,parseInt(rankType),1,0)
    hiddenyuepiao()

}
month.onclick = ()=>{
    day.classList.remove('span_active')
    month.classList.add('span_active')
    page.innerHTML =''
    periodType = 2
    getData(1,10,1,parseInt(rankType),1,2)
    hiddenyuepiao()
}
// 渲染分页组件
const renderPagination = () => {
        layui.use(function(){
            var laypage = layui.laypage;
            // 完整显示
            laypage.render({
            elem: 'demo-laypage-all', // 元素 id
            limit: 10,
            count: itemCount, // 数据总数
            layout: ['prev', 'page', 'next', 'skip'], // 功能布局
            curr: currentPage, // 初始获取 hash 值为 curr 的当前页
            hash: 'curr' ,// 自定义 hash 名称
            jump: function(obj, first){
                // console.log(obj.curr); // 得到当前页，以便向服务端请求对应页的数据。
                // console.log(obj.limit); // 得到每页显示的条数
                // 首次不执行
                if(!first){
                // do something
                currentPage = obj.curr
                getData(obj.curr, pageSize, 1, rankType, isNewBook)
                hiddenyuepiao()
                }
            }
            });
        });
}

getData()
// renderPagination()
const author_jump = (id)=>{
    window.location.href = 'naodongxingqiu_author.html?id=' +id
    console.log(id)
}

logn=()=>{
    window.location.href='naodongindex.html'
}
logn1=()=>{
    window.location.href='bookstock.html'
}
logn2=()=>{
    window.location.href='login.html'
}
logn3=()=>{
    window.location.href='books.html'
}
to=()=>{
    console.log(9999)
     const inputElement = document.querySelector('.search input');
    const searchText = inputElement.value.trim();
        console.log(searchText);
        inputElement.value = '';
        window.location.href = 'shearh.html?searchText=' + searchText;
}

ju=()=>{
    console.log(9999)
    window.location.href='detail.html'
}